#pragma once
#include<iostream>
#include<string.h>
#include<assert.h>
using namespace std;
namespace yjt
{
	class string
	{
	public:
		typedef char* iterator;
		iterator begin() { return _str; }
		iterator end() { return _str+_size; }

		string(const char* str = "")
		{
			_size = strlen(str);
			_capacity = _size;
			_str = new char[_capacity+1];

			strcpy(_str, str);
		}
		~string()
		{
			delete[] _str;
			_str = nullptr;
			_size = 0;
			_capacity = 0;
		}
		const char* c_str() { return _str; }
		size_t size() { return _size; }
		size_t capacity() { return _capacity; }
		char& operator[](int pos) 
		{ 
			assert(pos <= _size);
			return _str[pos]; 
		}
		void reserve(size_t n)
		{
			if (n > _capacity)
			{
				char* tmp = new char[n + 1];
				strcpy(tmp, _str);
				delete[] _str;
				_str = tmp;
				_capacity = n;
			}
		}
		void push_back(char ch)
		{
			if (_size == _capacity)
			{
				int newcapacity = _capacity == 0 ? 4 : 2 * _capacity;
				reserve(newcapacity);
			}
			_str[_size++] = ch;
		}
		void append(const char* str)
		{
			int len = strlen(str);
			if (_size + len > _capacity)
			{
				reserve(_size + len);
			}
			strcpy(_str + len, str);
			_size += len;
		}
		string& operator+=(char ch)
		{
			push_back(ch);
			return *this;
		}
		string& operator+=(const char* str)
		{
			append(str);
			return *this;
		}
		void insert(size_t pos, char ch)
		{
			assert(pos <= _size);
			if (_size == _capacity)
			{
				int newcapacity = _capacity == 0 ? 4 : 2 * _capacity;
				reserve(newcapacity);
			}
			int end = _size;
			while (end >= (int)pos)
			{
				_str[end + 1] = _str[end];
				--end;
			}
			_str[pos] = ch;
			_size++;
		}
		void insert(size_t pos, const char* str)
		{
			assert(pos <= _size);
			int len = strlen(str);
			if (_size + len > _capacity)
			{
				reserve(_size + len);
			}
			int end = _size;
			while (end >= (int)pos)
			{
				_str[end + pos] = _str[end];
				--end;
			}
			strncpy(_str + pos, str, len);
			_size += len;
		}
		void erase(size_t pos, size_t len = npos)
		{
			assert(pos < _size);

			if (len == npos || pos + len >= _size)
			{
				_str[pos] = '\0';
				_size = pos;
			}
			else
			{
				strcpy(_str + pos, _str + pos + len);
				_size -= len;
			}
		}
	private:
		int _size;
		int _capacity;
		char* _str;

		const static size_t npos = -1;
	};


	void test_string1()
	{
		yjt::string s1;
		yjt::string s2("hello world");
		cout << s2.c_str() << endl;
		for (int i = 0; i < s2.size(); i++)
		{
			cout << s2[i] << " ";
		}
		cout << endl;

		yjt::string::iterator it = s2.begin();
		while (it != s2.end())
		{
			cout << *it << " ";
			it++;
		}
		cout << endl;
	}

	void test_string2()
	{
		string s2("hello world");
		s2 += ' ';
		s2 += "1234";
		cout << s2.c_str() << endl;

		s2.insert(5, 'y');
		s2.insert(5, 'y');
		s2.insert(5, 'y');
		s2.insert(5, 'y');
		cout << s2.c_str() << endl;

		s2.insert(1, "zzzz");
		cout << s2.c_str() << endl;

	}
}